﻿using Orchard.Autoroute.Models;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Handlers;
using Orchard.Taxonomies.Fields;
using System.Linq;

namespace IvyExcellence.HierarchicalUrls.Handlers
{
    public class AliasHandler : ContentHandler
    {
        public AliasHandler()
        { 
            OnPublishing<AutoroutePart>((ctx, part) =>
            {
               if (!part.ContentItem.HasPublished() && !part.DisplayAlias.Equals("/"))
               {
                   var channels = (TaxonomyField)part.Fields.FirstOrDefault(f => f.PartFieldDefinition.Name.Equals("Channels"));
                   if (channels.Terms != null && channels.Terms.Any())
                       part.DisplayAlias = channels.Terms.First().Slug + "/" + part.DisplayAlias;
               }
            });

        }
    }
}